const { connect } = require("http2");
const mysql = require("mysql");
const db = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123456',
    port     : '3306',
    database : 'my_school_project_database'
})
const store = require("../stores/data");
db.connect(err=>{
    console.log(err);
});

// 前台系统使用
module.exports.client = {
    // 分页器
    pager(req, res, next){
        // pageNo 当前页；pageSize 一页多少个；
        const {pageNo, pageSize} = req.query;
        req.pageNo = pageNo;
        req.pageSize = pageSize;
        next();
    },
    // 从服务器中获取rooms表全部数据。
    getRoomsListData:(req, res, next)=>{
        // 查询总共有多少条数据
        const sql_all = 'SELECT count(*) FROM roomtype;';
        db.query(sql_all, (err, result)=>{
            if(err){
                console.log(err);
            }else{
                // 结果向上取整
                res.total = parseInt(result[0]['count(*)']);
                res.maxPage = Math.ceil(res.total/req.pageSize);
            }
        })

        // 找数据库要数据("初始位置","记录数")
        if(req.pageNo > res.maxPage){
            req.pageNo = res.maxPage;
            req.pageSize = res.total % req.pageSize;
        };
        const sql = "SELECT * FROM roomtype LIMIT ?,?;";
        const startPosition = req.pageSize * (req.pageNo-1);
        
        db.query(sql, [startPosition, parseInt(req.pageSize)], (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                res.code=200;
                res.message="GET ROOMSDATA IS SUCCESS.";
                res.data={
                    pageNo:req.pageNo,
                    pageSize:req.pageSize,
                    total:res.total,
                    result,
                };
                store.roomsListData = result;
                next();
            }
        })
    },
    // 从服务器中获取roomtype表 指定房型 的全部房间数据。-1:全部类型
    getRoomsSelectData:(req, res, next)=>{
        if(store.roomsSelectData){
            res.code=200,
            res.message="GET ROOMSSELECTDATA IS SUCCESS.";
            res.data = store.roomsSelectData;
            next();
        }

        const value = req.query.classifyId;
        let sql = "SELECT * FROM roomtype WHERE typeNum=?;";
        if(value==-1){
            sql = "SELECT * FROM roomtype;"; 
        }
        db.query(sql, value, (err, result)=>{
            if(err){
                res.code=500,
                res.message=err.message,
                res.data={}
            }else{
                res.code=200,
                res.message="GET ROOMSSELECTDATA IS SUCCESS.";
                res.data = result;
                store.roomsSelectData = result;
                next();
            }
        })
    },
    // 根据房间id在数据仓库中获取房间信息。
    getStoreRoomDataOfRoomId:(req, res, next)=>{
        const {typeNum} = req.query;
        store.roomsListData.forEach(element => {
            if(element.typeNum == typeNum){
                res.roomData = element;
            }
        });
        next();
    },
    // 向数据库orders表中插入 新的申请入住订单 。
    createOrder:(req, res, next)=>{
        const sql = "INSERT INTO orders (createTime,state,userIdArr,customerName,customerPhone,totalPrice,inTime,outTime,roomType,images,typeName) VALUE (?,?,?,?,?,?,?,?,?,?,?);";
        const {createTime,userId,customerName,customerPhone,totalPrice,inTime,outTime,typeNum} = req.query;
        if(totalPrice<0){
            res.coed = 500;
            res.message = "THE ORDER PRICE IS ERROR.;";
            res.data = {};
            next();
        }
        const {images,typeName} = res.roomData;
        const state = 3;
        const value = [
            createTime,
            state,
            userId,
            customerName,
            customerPhone,
            totalPrice,
            inTime,
            outTime,
            typeNum,
            images,
            typeName
        ];
        db.query(sql, value, (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                res.code=200;
                res.message="CREATEORDER IS SUCCESS.";
                res.data={};
                next();
            }
        });
    },
    // 在数据库users表中 插入一条新的用户数据（用户id以时间戳生成）。
    createUser:(req, res, next)=>{
        const {user,name,password,phone,createTime,gender} = req.query;
        const sql = "INSERT INTO users (user,userName,password,userPhone,createTime,userGender) VALUE (?,?,?,?,?,?);";
        const value = [
            user,
            name,
            password,
            phone,
            createTime,
            gender
        ];
        db.query(sql, value, (err, result)=>{
            if(err){
                switch(err.sqlState){
                    case '23000':
                        res.message = "账号已存在，请重新输入！";
                        break;
                    default:
                        res.message=err.message;
                }
                res.code=500;
                res.data={};
                next();
            }else{
                res.code=200;
                res.message="CREATEUSER IS SUCCESS.";
                res.data={};
                next();
            }
        })
    },
    // 根据user从users表中获取password校验账密
    loginUser(req, res, next){
        req.info = req.query;
        const sql = "SELECT password FROM users WHERE user=?;"
        const {user} = req.info;
        if(user == '') {
            res.code=401;
                res.message='THE USER IS NOT NULL';
                res.data={};
                next();
        }
        db.query(sql, user, (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else if(result.length == 0){
                res.code=502;
                res.message="THE ACCOUNT NOT REGISTERED.";
                res.data={};
                next();
            }else if(result[0].password == req.info.password){
                res.code=200;
                res.message="THE ACCOUNT PASSWORD ARE CONSISTENT.";
                res.data={};
                next();
            }else{
                res.code=501;
                res.message="THE ACCOUNT PASSWORD IS DIFFERENT.";
                res.data={};
                next();
            }
        })
    },
    // 验证账密是否一致，如果一致生成TOKEN，并将在users表中修改TOKEN。
    loginToken(req, res, next){
        if(res.code>=300){
            next();
        }else{
            res.token = "Happy"+Date.now();
            const sql = "UPDATE users SET token=? WHERE user=?;";
            const value = [res.token, req.info.user];
            db.query(sql, value, (err, result)=>{
                if(err){
                    res.code=502;
                    res.message=err.message;
                    res.data={};
                    next();
                }else{
                    res.code=200;
                    res.message="THE USER IS LOGIN IS SUCCESS.";
                    res.data={token:res.token};
                    next();
                }
            })
        }
    },
    // 从数据库users表中获取对应token的用户指定数据(userId、name、phone、userPicture、userBalance)。
    getUserInfoOfToken(req, res, next){
        const sql = "SELECT * FROM users WHERE token=?;";
        const token = req.headers.accesstoken;
        db.query(sql, token, (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                if(result.length > 0){
                    const {userId,userName,userPhone,userPicture,userBalance} = result[0];
                    const tokenUser = {
                        token,
                        data:{
                            userId,
                            userName,
                            userPhone,
                            userPicture,
                            userBalance
                        }
                    }
                    store.tokenUserList[token]= tokenUser;
                    res.code = 200;
                    res.message = "GETUSERINFOOFTOKEN IS SUCCESS.";
                    res.data = tokenUser.data;
                    next();
                }else{
                    res.code = 501;
                    res.message = "SELECT MYSQL IS NOT THIS TOKEN.";
                    res.data = {};
                    console.log(`getUserInfoOfToken this token is not select, token=${token}`)
                    next();
                }
            }
        })
    },
    // 根据token拿到用户的userId，再从数据库orders表中获取该用户的全部订单信息。
    getUserAllOrdersList(req, res, next){
        try{
            const token = req.headers.accesstoken;
            const {userId} = store.tokenUserList[token].data;
            const sql = "SELECT * FROM orders WHERE userIdArr LIKE ?;";
        db.query(sql, userId, (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                res.code = 200;
                res.message = "GET USER ORDER SUCCESS.";
                res.data = result;
                next();
            }
        })
        }catch(err){
            console.log(err.message);
            next();
        }
    },
    // 获取订单id，新的（用户名、电话号码），修改数据库中的订单信息。
    updateOrderInfo(req, res, next){
        let {name,phone,orderId} = req.query;
        let sql = "UPDATE orders SET customerName = ?, customerPhone = ? WHERE orderId = ?";
        let value = [name, phone, orderId];
        db.query(sql, value, (err, result)=>{
            if(err){
                res.code=501;
                res.message=err.message;
                res.data={};
                next();
            }else{
                res.code=200;
                res.message="UPDATE ORDERINFO IS SUCCESS.";
                res.data={};
                next();
            }
        });
    },
    // 获取用户最新的余额数据。
    getUserBalance(req, res, next){
        const token = req.headers.accesstoken;
        const sql = "SELECT userBalance FROM users WHERE token=?;";
        db.query(sql, token, (err, result)=>{
            if(err){
                res.code=502;
                res.message=err.message;
                next();
            }else{
                res.code=200;
                res.message="GET USERBALANCE IS SUCCESS.";
                res.userBalance=parseFloat(result[0].userBalance);
                next();
            }
        })
    },
    // 将新的余额数存入数据库中。
    updateUserBalance(req, res, next){
        if(res.code>=500) next();

        const token = req.headers.accesstoken;
        const newBalance = res.userBalance + parseFloat(req.query.addBalance);
        const sql = "UPDATE users SET userBalance=? WHERE token=?;";
        const value = [newBalance, token];
        db.query(sql, value, (err, result)=>{
            if(err){
                res.code=502;
                res.message=err.message;
                next();
            }else{
                res.code=200;
                res.message="UPADTE userBalance IS SUCCESS.";
                next();
            }
        })
    },
    //获取最新的用户余额，根据token获取。
    getNewUserBalance(req, res, next){
        if(res.code>=500) next();

        const token = req.headers.accesstoken;
        const sql = "SELECT userBalance FROM users WHERE token=?;";
        db.query(sql, token, (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                res.code=200;
                res.message="USERBALANCE TOPUP IS SUCCESS.";
                res.data=result[0];
                next();
            }
        })
    },
    // 通过orderId、userId获取用户订单，
    getOrderInfo(req, res, next){
        res.orderId = req.query.orderId;
        const sql = "SELECT totalPrice FROM orders WHERE orderId=?;";
        db.query(sql, [res.orderId], (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                res.code=200;
                res.message="GET ORDERINFO IS SUCCESS.";
                res.data={};
                res.orderPrice = parseFloat(result[0].totalPrice);
                next();
            }
        })
    },
    // 进行支付订单处理，并将新的余额更新到users表中。
    payOrder(req, res, next){
        if(res.code>=500){
            next();
        }else{
            if(res.userBalance>=res.orderPrice){
                res.newUserBalance=res.userBalance-res.orderPrice;
                const sql = "UPDATE users SET userBalance=? WHERE userId=?;";
                db.query(sql, [res.newUserBalance, res.userId], (err, result)=>{
                    if(err){
                        res.code=500;
                        res.message=err.message;
                        res.data={};
                        next();
                    }else{
                        res.code=200;
                        res.message="PAY ORDER IS SUCCESS.";
                        res.data={};
                        next();
                    }
                })
            }else{
                res.code=500;
                res.message="INSUFFICIENT BALANCE.";
                res.data={};
                next();
            }
        }
    },
    // 更新订单状态state。
    updateOrderState(req, res, next){
        if(res.code>=500){
            next();
        }else{
            const sql = "UPDATE orders SET state=4 WHERE orderId=?;";
            db.query(sql, res.orderId, (err, result)=>{
                if(err){
                    res.code=500;
                    res.message=err.message;
                    res.data={};
                    next();
                }else{
                    res.code=200;
                    res.message="THE USER PAY ORDER IS SUCCESS.";
                    res.data={};
                    next();
                }
            })
        }
    },
    // 获取指定orderId的订单信息
    getOrderInfoByOrderId(req, res, next){
        const {orderId} = req.query;
        const sql = "SELECT * FROM orders WHERE orderId=?;";
        db.query(sql, orderId, (err, result)=>{
            if(err){
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                res.code=200;
                res.message="SELECT IS SUCCESS.";
                res.data={};
                res.orderInfo=result[0];
                next();
            }
        })
    },
    // 设置订单为取消状态
    cancelOrder(req, res, next){
        if(res.code==500){
            next();
        }else{
            switch(res.orderInfo.state){
                case '3':   //3表示用户还未支付该订单，因此无需退款。
                    res.needRefund = false;
                    break;
                case '0':   //0表示用户已经支付过该订单，并且未核销，因此需要退款。
                    res.needRefund = true;
                    break;
                case '1':   //1表示用户已经使用了该订单，因此无需退款。
                    res.needRefund = false;
                    break;
                case '4':   //4表示还没有分配房间，此时用户还未支付，因此无需退款。
                    res.needRefund = false;
                    break;
            }
            // 将订单状态改为2取消
            const sql = "UPDATE orders SET state=2 WHERE orderId=?;";
            db.query(sql, res.orderInfo.orderId, (err, result)=>{
                if(err){
                    res.code=500;
                    res.message=err.message;
                    res.data={};
                    next();
                }else{
                    res.code=200;
                    res.message="THE USER PAY ORDER IS SUCCESS.";
                    res.data={};
                    next();
                }
            })
        }
    },

    // 为订单退款，更新用户余额
    refundOrderPrice(req, res, next){
        if(!res.needRefund) {
            next()
        }else{
            const token = req.headers.accesstoken;
            let orderPrice = parseFloat(res.orderInfo.totalPrice);
            let newUserBalance = res.userBalance+orderPrice;
            const sql = "UPDATE users SET userBalance=? WHERE token=?;";
            const value = [newUserBalance, token];
            db.query(sql, value, (err, result)=>{
                if(err){
                    res.code=503;
                    res.message=err.message;
                    next();
                }else{
                    res.code=200;
                    res.message="REFUND userBalance IS SUCCESS.";
                    next();
                }
            })
        }
    }
}

// 后台系统使用
module.exports.back = {
    // 新增房间
    addRoom:(req, res, next)=>{
        let {roomNum, roomType, roomMoney} = req.query;
        let now = Date.now();
        const sql = 'INSERT INTO roomlist (roomNum, roomType, price, createTime, updateTime, state) VALUE (?,?,?,?,?,?);';
        let sqlValue = [roomNum, roomType, roomMoney, now, now, '0'];
        db.query(sql, sqlValue, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('addRoom is Sucess.');
                res.code=200;
                res.message = 'success.';
                res.data = {};
                next();
            }
        })

    },

    // 获取房间列表
    getRoomListData:(req, res, next)=>{
        const sql = 'SELECT * FROM roomlist;';
        db.query(sql, (err, result)=>{
            if(err){
                console.log(err);
                res.code = 500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('getRoomList is Success.');
                res.code = 200;
                res.message = 'Success.';
                res.data = result;
                next();
            }
        })
    },

    // 修改房间配置
    modifyRoomConfig:(req, res, next)=>{
        const now = Date.now();
        const {roomId, roomNum, roomType, roomMoney} = req.query;
        const sql = 'UPDATE roomlist SET roomNum=?,roomType=?,price=?,updateTime=? WHERE roomId=?;';
        const sqlValue = [roomNum, roomType, roomMoney, now, roomId];
        db.query(sql, sqlValue, (err,result)=>{
            if (err){
                console.log(err);
                res.code = 500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('modifyRoomConfig is Success.');
                res.code = 200;
                res.message = 'Success.';
                res.data = {};
                next();
            }
        })
    },

    // 删除房间
    deleteRoom:(req, res, next)=>{
        const {roomId} = req.query;
        const sql = 'DELETE FROM roomlist WHERE roomId=?;';
        db.query(sql, roomId, (err, result)=>{
            if (err){
                console.log(err);
                res.code = 500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('deleteRoom is Success.');
                res.code = 200;
                res.message = 'Success.';
                res.data = {};
                next();
            }
        })
    },

    // 新增房间类型
    addRoomType:(req, res, next)=>{
        const {typeNum, typeName, typePrice, describe, labels} = req.query;
        const sql = 'INSERT INTO roomtype (typeNum, typeName, typePrice, des, labels) VALUES (?,?,?,?,?);';
        db.query(sql, [typeNum, typeName, typePrice, describe, labels], (err, result)=>{
            if (err){
                console.log(err);
                res.code = 500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('addRoomType is Success.');
                res.code = 200;
                res.message = 'Success.';
                res.data = {};
                next();
            }
        })
    },

    // 获取房间类型列表
    getRoomType:(req, res, next)=>{
        const sql = 'SELECT * FROM roomtype;';
        db.query(sql, (err, result)=>{
            if (err){
                console.log(err);
                res.code = 500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('getRoomType is Success.');
                res.code = 200;
                res.message = 'Success.';
                res.data = result;
                next();
            }
        })
    },

    // 修改房间类型(ps:2023年3月5日暂时先排除images属性)
    modifyRoomTypeConfig:(req, res, next)=>{
        const {typeId, typeNum, typeName, typePrice, describe, labels} = req.query;
        const sql = 'UPDATE roomtype SET typeNum=?,typeName=?,typePrice=?,des=?,labels=? WHERE typeId=?;';
        db.query(sql, [typeNum,typeName,typePrice,describe,labels,typeId], (err, result)=>{
            if (err){
                console.log(err);
                res.code = 500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('modifyRoomTypeConfig is Success.');
                res.code = 200;
                res.message = 'Success.';
                res.data = {};
                next();
            }
        })
    },

    // 删除房间类型
    deleteRoomType:(req, res, next)=>{
        const {typeId} = req.query;
        const sql = 'DELETE FROM roomtype WHERE typeId=?;';
        db.query(sql, typeId, (err, result)=>{
            if (err){
                console.log(err);
                res.code = 500;
                res.message = err.message;
                res.data = {};
                next();
            }else{
                console.log('deleteRoomType is Success.');
                res.code = 200;
                res.message = 'Success.';
                res.data = {};
                next();
            }
        })
    },

    // 获取用户列表['用户名'、'用户ID']
    getUserList:(req, res, next)=>{
        const sql = 'SELECT userName,userId FROM users;';
        db.query(sql, (err, result)=>{
            if (err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('getUserList is Success.');
                res.code=200;
                res.message='Succes.';
                res.data=result;
                next();
            }
        })
    },

    // 根据用户id列表获取用户信息列表
    getUserInfoList:(req, res, next)=>{
        const {userIdArr} = req.query;
        const sql = 'SELECT userId,userName,userGender,userIdNumber,userPhone FROM users WHERE FIND_IN_SET(userId,?);';
        console.log(userIdArr)
        db.query(sql, userIdArr, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('getUserInfoList is Success.');
                res.code=200;
                res.message='Success.';
                res.data=result;
                next();
            }
        })
    },

    // 根据choiceOrderId判断是否线下开房
    openCheck:(req, res, next)=>{
        const {choiceOrderId, roomId} = req.query;
        req.orderId = choiceOrderId;
        req.roomId = roomId;
        if(choiceOrderId==null || choiceOrderId=='' || choiceOrderId==0) next;
        const sql = 'UPDATE orders SET roomId=?,state=0 WHERE orderId=?';
        db.query(sql, [roomId, choiceOrderId], (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('openCheck is Succes.');
                res.code=200;
                res.message='Success.';
                res.data={};
                res.openCheck = true;
                next();
            }
        })
    },

    // 创建订单（开房）
    openRoom:(req, res, next)=>{
        if(res.openCheck) next();
        const {openInfo, roomId, createTime} = req.query;
        req.roomId = roomId;
        const userIdArr = openInfo.userIdArr.join(',');
        const sql = 'INSERT INTO orders (createTime,userIdArr,roomId,totalPrice,inTime,outTime,state) VALUES (?,?,?,?,?,?,?);';
        const value = [
            createTime,
            userIdArr,
            roomId,
            openInfo.totalPrice,
            openInfo.date1,
            openInfo.date2,
            '0'
        ]
        db.query(sql, value, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('openRoom is Succes.');
                res.code=200;
                res.message='Success.';
                res.data={};
                next();
            }
        })
    },

    // 根据房间Id获取订单Id
    getOrderId:(req, res, next)=>{
        if(res.openCheck) next();
        const sql = 'SELECT orderId FROM orders WHERE roomId=?;';
        db.query(sql, req.roomId, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('modifyRoomStateToOpen is Succes.');
                res.code=200;
                res.message='Success.';
                res.data={};
                req.orderId = result[0].orderId;
                next();
            }
        })
    },

    // 根据房间Id修改房间状态（state=1, 添加orderId）
    modifyRoomStateAndOrderId:(req, res, next)=>{
        const sql = 'UPDATE roomlist SET state=1,orderId=? WHERE roomId=?;';
        db.query(sql, [req.orderId, req.roomId], (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('modifyRoomStateAndOrderId is Succes.');
                res.code=200;
                res.message='Success.';
                res.data={};
                next();
            }
        })
    },

    // 获取全部待核销的订单（state=0）
    getAllStateZeroOrderList:(req, res, next)=>{
        const sql = 'SELECT * FROM orders WHERE state=0;';
        db.query(sql, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('getAllStateZeroOrderList is Success.');
                res.code=200;
                res.message='Success.';
                res.data=result;
                next();
            }
        })
    },

    // 根据orderId获取订单
    getOrderInfo:(req, res, next)=>{
        const {orderId} = req.query;
        const sql = 'SELECT * FROM orders WHERE orderId=?;';
        db.query(sql, orderId, (err, result)=>{
            if (err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('getOrderInfo is Success.');
                res.code=200;
                res.message='Success.';
                res.data=[];
                res.data.push(result[0]);
                next();
            }
        })
    },

    // 退房-1：修改房间状态state=0
    closeRoomForRoomList:(req, res, next)=>{
        const {roomId} = req.query;
        const sql = 'UPDATE roomlist SET orderId="",state=0 WHERE roomId=?;';
        db.query(sql, roomId, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('closeRoomForRoomList is Success.');
                res.code=200;
                res.message='Success.';
                res.data={};
                next();
            }
        })
    },

    // 退房-2：修改订单状态state=1
    closeRoomForOrders:(req, res, next)=>{
        const {orderId} = req.query;
        const sql = 'UPDATE orders SET state=1 WHERE orderId=?;';
        db.query(sql, orderId, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('closeRoomForOrders is Success.');
                res.code=200;
                res.message='Success.';
                res.data={};
                next();
            }
        })
    },

    // 换房-1：修改订单roomId
    changeRoomForOrder:(req, res, next)=>{
        const {orderId, changeRoomId} = req.query;
        const sql = 'UPDATE orders SET roomId=? WHERE orderId=?;';
        db.query(sql, [changeRoomId, orderId], (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('changeRoomForOrder is Success.');
                res.code=200;
                res.message='Success';
                res.data={};
                next();
            }
        })
    },
    // 换房-2：给roomlist新房间添加OrderId
    changeRoomForNewRoom:(req, res, next)=>{
        if(res.code==500) next();
        const {orderId, changeRoomId} = req.query;
        const sql = 'UPDATE roomlist SET orderId=?,state=1 WHERE roomId=?;';
        db.query(sql, [orderId, changeRoomId], (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('changeRoomForNewRoom is Success.');
                res.code=200;
                res.message='Success';
                res.data={};
                next();
            }
        })
    },
    // 换房-3：给roomlist旧房间清除OrderId
    changeRoomForOldRoom:(req, res, next)=>{
        if(res.code==500) next();
        const {roomId} = req.query;
        const sql = 'UPDATE roomlist SET orderId="",state=0 WHERE roomId=?;';
        db.query(sql, roomId, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('changeRoomForOldRoom is Success.');
                res.code=200;
                res.message='Success';
                res.data={};
                next();
            }
        })
    },

    // 查询订单-1：根据用户id查询所有订单状态为1的订单信息
    getOrderListByUserId:(req, res, next)=>{
        const {userId} = req.query;
        const sql = 'SELECT * FROM orders WHERE FIND_IN_SET(?, userIdArr);';
        db.query(sql, userId, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('getOrderListByUserId is Success.');
                res.code=200;
                res.message='Success.';
                res.data=result;
                next();
            }
        })
    },

    // 获取线上待分配订单
    getOnlineOrderList:(req, res, next)=>{
        const sql = 'SELECT * FROM orders WHERE state=4';
        db.query(sql, (err, result)=>{
            if(err){
                console.log(err);
                res.code=500;
                res.message=err.message;
                res.data={};
                next();
            }else{
                console.log('getOnlineOrderList is Success.');
                res.code=200;
                res.message='Success.';
                res.data=result;
                next();
            }
        })
    },
}

// upload使用
module.exports.upload = {
    
}
